package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MybatisUtils {
    private MybatisUtils(){

    }
    public static SqlSessionFactory factory;

    static {
        try {
            InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
       return  factory.openSession();

    }

    public static Object getMapper(Class mapperClass){
        // 获取sqlSession对象
        SqlSession sqlSession = getSqlSession();
        // 获取mapper接口
        Object mapper = sqlSession.getMapper(mapperClass);

        // 动态代理 实现mapper增强
        Object mapper_Proxy  =  Proxy.newProxyInstance(mapper.getClass().getClassLoader(), mapper.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = method.invoke(mapper, args);
                try {
                    //成功提交
                    sqlSession.commit();
                } catch (Exception e) {
                    //失败回滚
                    sqlSession.rollback();
                    e.printStackTrace();
                }  finally {
                    //释放资源
                    sqlSession.close();
                }
                return result;
            }
        });
       return mapper_Proxy;
    }
}
